﻿using MesGLApp.DAL.RoleDB;
using MesGLApp.Tools;
using MesGLApp.View;
using LinqKit;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Xml.Linq;

namespace MesGLApp.BLL.Role
{
    public class RoleInfoControler
    {

        /// <summary>
        /// 获取角色数据
        /// </summary>
        /// <param name="name">角色名称</param>
        /// <returns></returns>
        public List<BaseRoleModel> getRoles(string name = "")
        {
            List<BaseRoleModel> resList = new List<BaseRoleModel>();
            using (RoleDB db = new RoleDB())
            {
                IQueryable query = null;
                if (name != null && name.ToString().Trim().Length > 0)
                {
                    query = db.base_role.Where(u => u.role_name.Contains(name))
                                            .OrderBy(u => u.id);
                }
                else
                {
                    query = db.base_role.OrderByDescending(u => u.id);
                }

                if (query != null)
                {
                    foreach (BaseRoleModel tmpBean in query)
                    {
                        resList.Add(tmpBean);
                    }
                }
            }
            return resList;
        }


        /// <summary>
        /// 获取角色信息
        /// </summary>
        /// <param id="id">角色id</param>
        /// <returns></returns>
        public BaseRoleModel getRoleInfo(int id)
        {
            var roleInfo = new BaseRoleModel();
            using (RoleDB db = new RoleDB())
            {
                var query = db.base_role.Where(u => u.id == id).FirstOrDefault();

                roleInfo = query;
            }

            return roleInfo;
        }



        public int getRoleLastId()
        {
            int LastId = 0;
            using (RoleDB db = new RoleDB())
            {
                var query = db.base_role.OrderByDescending(o => o.id).First();

                if (query != null)
                {
                    LastId = query.id;
                }

            }

            return LastId;
        }



        public int saveRoleInfo(BaseRoleModel role)
        {
            if (role != null)
            {
                using (RoleDB db = new RoleDB())
                {
                    var tran = db.Database.BeginTransaction();
                    try
                    {
                        var query1 = db.base_role
                                .Where(u => u.role_name.Equals(role.role_name))
                                .Where(u => u.id != role.id).ToList();
                        if (query1.Count == 0)
                        {
                            var query2 = db.base_role
                                          .Where(u => u.id == role.id).FirstOrDefault();
                            if (query2 == null)
                            {
                                var roleCode = db.Database.SqlQuery<string>("getLsh @p",
                                         new SqlParameter("@p", "Role")).First();
                                role.role_code = roleCode;
                                db.base_role.Add(role);
                            }
                            else
                            {
                                db.base_role.AddOrUpdate(role);
                            }
                            int count = db.SaveChanges();
                            tran.Commit();
                            return count;
                        }
                        else
                        {
                            tran.Rollback();
                            throw new Exception("角色名称已存在");
                        }
                    }
                    catch (Exception)
                    {
                        tran.Rollback();
                        throw new Exception("角色添加或修改异常");
                    }

                }
            }
            else
            {
                throw new Exception("传入的角色为空，中止保存！");
            }
        }


        public int delRole(int id)
        {
            using (RoleDB db = new RoleDB())
            {
                try
                {
                    var query1 = db.base_role.Where(u => u.id == id).FirstOrDefault();
                    db.base_role.Remove(query1);
                    int count = db.SaveChanges();
                    return count;
                }
                catch (Exception)
                {
                    throw new Exception("角色删除异常");
                }
            }
        }


        public List<TreeNode> getMenuTreeNodes(int roid, int pid = 0)
        {
            var menuNode = new List<TreeNode>();
            using (RoleDB db = new RoleDB())
            {
                var menus = db.base_menu.Where(u => u.parent_id == pid && u.base_prog_id == LoginFrm.ProgInfo.id)
                            .OrderBy(u => u.sort)
                            .ToList();

                foreach (var menu in menus)
                {
                    TreeNode node = new TreeNode();
                    node.Name = menu.id.ToString();
                    node.Text = menu.menu_name.ToString();
                    var IsCheck = db.base_role_menu.Where(u => u.base_menu_id == menu.id
                                  && u.base_role_id == roid).FirstOrDefault();
                    node.Checked = IsCheck != null ? true : false;
                    node.Nodes.AddRange(getMenuTreeNodes(roid, menu.id).ToArray());
                    menuNode.Add(node);
                }
            }

            return menuNode;
        }

        public int updateAuthRole(int roid,List<BaseRoleMenuModel> baseRoleMenuModels) 
        {
            int[] menuIds;
            using (RoleDB db = new RoleDB()) 
            {
                menuIds = db.base_menu.Where(s => s.base_prog_id == LoginFrm.ProgInfo.id)
                           .Select(s => s.id)
                           .ToArray();

                var roleMenus = db.base_role_menu
                                .Where(w => w.base_role_id == roid
                                && menuIds.Contains(w.base_menu_id))
                                .ToList();

                db.base_role_menu.RemoveRange(roleMenus);

                db.base_role_menu.AddRange(baseRoleMenuModels);

                int res =db.SaveChanges();

                return res;

                //if (res > 0)
                //{
                //    SysTools.errMessage(200, "授权成功");
                //} 
                //else
                //{
                //    SysTools.errMessage(0, "授权失败");  
                //};
            }
        
        }



        //public DataTable getUserRoles(int user_id = 0,string name="") 
        //{ 
        //    var userRoles = new DataTable();

        //    using (RoleDB db = new RoleDB())
        //    {

        //        var query = from a in db.base_user
        //                    join b in db.base_user_role on a.id equals b.base_user_id into left_ab
        //                    from ab in left_ab.DefaultIfEmpty()
        //                    join c in db.base_role on ab.base_role_id equals c.id into left_abc
        //                    from abc in left_abc.DefaultIfEmpty()
        //                    select new {
        //                        id = a.id,
        //                        user_name = a.user_name,
        //                        real_name = a.real_name,
        //                        base_role_id = ab.base_role_id != null ? ab.base_role_id : 0,
        //                        role_name = abc.role_name,
        //                        create_user = ab.create_user,
        //                        create_date = ab.create_date,
        //                        update_date = ab.update_date
        //                    };

        //        if (user_id != 0) 
        //        { 
        //            query =  query.Where(u=>u.id==user_id);
        //        }

        //        if (name != "")
        //        {
        //            query = query.Where(u => u.real_name.Contains(name));
        //        }

        //        userRoles = query.ToList().ToDataTable();

        //    }

        //  return userRoles;
        //}


        public int saveUserRole(BaseUserRoleModel baseUserRoleModel) 
        {
            using (RoleDB db = new RoleDB())
            {

                var query = db.base_user_role.Where(
                    u=>u.base_user_id == baseUserRoleModel.base_user_id)
                    .FirstOrDefault();


                if (query != null)
                {
                    query.base_role_id = baseUserRoleModel.base_role_id;
                    query.update_date = DateTime.Now;
                }
                else
                {
                    baseUserRoleModel.create_user = LoginFrm.LoginUser.user_name;
                    baseUserRoleModel.create_date = DateTime.Now;
                    db.base_user_role.Add(baseUserRoleModel);
                }

                int res = db.SaveChanges();
                return res;
            }


        }

    }
}
